package com.capybara.account.base;

import com.capybara.account.result.Result;
import com.capybara.account.result.ResultSet;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 处理程序异常解析器
 *
 * @author guochaowang
 * @date 2024/09/14
 */
@Slf4j
@Data
public class MyHandlerExceptionResolvers implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(
            @NonNull HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            @NonNull Exception ex
    ) {
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        try {
            Result<?> error;
//            if (ex instanceof AuthorizationDeniedException) {
//                error = ResultSet.error401("授权被拒绝异常");
//            } else if (ex instanceof InvalidBearerTokenException) {
//                error = ResultSet.error401("token异常");
//            } else if (ex instanceof MyLoginException le) {
//                error = ResultSet.error401(le.getError().getErrorCode());
//            } else if (ex instanceof IllegalArgumentException) {
//                error = ResultSet.error("非法参数异常");
//            } else if (ex instanceof NoSuchElementException) {
//                error = ResultSet.error("未找到记录");
//            } else if (ex instanceof MyServiceException) {
//                //自定义业务异常处理
//                error = ResultSet.error(ex.getMessage());
            if (ex instanceof MethodArgumentNotValidException m) {
                // 校验提示
                List<ObjectError> allErrors = m.getBindingResult().getAllErrors();
                String message = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
                error = ResultSet.error(message);
            } else {
                //500 内部错误
                error = ResultSet.error("系统繁忙，请稍后再试！");
                for (StackTraceElement element : ex.getStackTrace()) {
                    log.error(element.getClassName());//
                }
                log.error(ex.getMessage());//500
            }
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(error));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return new ModelAndView();
    }
}
